package com.tfjybj.itoo.exam.provider.controller;

import com.dmsdbj.itoo.tool.business.ItooResult;
import com.dmsdbj.itoo.tool.fastdfs.FastDfsUtil;
import com.github.pagehelper.PageInfo;
import com.tfjybj.itoo.exam.entity.DatumEntity;
import com.tfjybj.itoo.exam.model.DatumModel;
import com.tfjybj.itoo.exam.provider.service.DatumService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * DatumController
 * datum表
 *
 * @author 贾建清
 * @version 2.0.0
 * @since 2.0.0 2018-12-08 12:31:48
 */
@Api(tags = {"datum表接口"})
@RequestMapping(value = "/datum")
@RestController
@Slf4j
public class DatumController {

    private static final String URL = "classpath:fast_client.conf";
    @Resource
    private DatumService datumService;

    //region 模板生成：基本增删改

    /**
     * 添加
     *
     * @param model DatumModel
     * @return 添加的结果
     * @author 贾建清
     * @since 2.0.0 2018-12-08 12:31:48
     */
    @ApiOperation(value = "添加")
    @PostMapping(value = {"/create"})
    public ItooResult create(@RequestBody DatumModel model) {
        if (StringUtils.isEmpty(model.getQuestionTypeId())) {
            return ItooResult.build(ItooResult.FAIL, "questionTypeId为空");
        }
        DatumEntity datumEntity = new DatumEntity();
        BeanUtils.copyProperties(model, datumEntity);
        datumService.save(datumEntity);
        return ItooResult.build(ItooResult.SUCCESS, "添加成功");
    }

    /**
     * 删除
     *
     * @param id 主键id
     * @return ItooResult 是否删除成功
     * @author 贾建清
     * @since 2.0.0 2018-12-08 12:31:48
     */
    @ApiOperation(value = "根据id删除（单个）")
    @DeleteMapping(value = {"/delete/{id}"})
    public ItooResult delete(@ApiParam(value = "主键id", required = true) @PathVariable String id) {
        datumService.removeById(id);
        return ItooResult.build(ItooResult.SUCCESS, "删除成功");
    }

    /**
     * 批量删除
     *
     * @param ids ids
     * @return ItooResult 批量删除是否成功结果
     * @author 贾建清
     * @since 2.0.0 2018-12-08 12:31:48
     */
    @ApiOperation(value = "根据id批量删除")
    @DeleteMapping(value = {"/deleteByIds"})
    @ApiImplicitParam(name = "ids", value = "ids", dataType = "List<String>", required = true)
    public ItooResult deleteByIds(@RequestBody List<String> ids) {
        datumService.removeByIds(ids);
        return ItooResult.build(ItooResult.SUCCESS, "批量删除成功");
    }

    /**
     * 修改
     *
     * @param model DatumModel
     * @return 修改后的结果
     * @author 贾建清
     * @since 2.0.0 2018-12-08 12:31:48
     */
    @ApiOperation(value = "根据id修改datum")
    @PutMapping(value = {"/modify"})
    public ItooResult modify(@RequestBody DatumModel model) {
        if (StringUtils.isEmpty(model.getQuestionTypeId())) {
            return ItooResult.build(ItooResult.FAIL, "questionTypeId为空");
        }
        DatumEntity datumEntity = new DatumEntity();
        BeanUtils.copyProperties(model, datumEntity);
        datumService.updateById(datumEntity);
        return ItooResult.build(ItooResult.SUCCESS, "修改成功");
    }

    /**
     * 根据id查找Datum
     *
     * @param id 主键id
     * @return 根据id查找的结果
     * @author 贾建清
     * @since 2.0.0 2018-12-08 12:31:48
     */
    @ApiOperation(value = "根据id查询")
    @GetMapping(value = {"/findById/{id}"})
    public ItooResult findById(@ApiParam(value = "主键id", required = true) @PathVariable String id) {
        DatumEntity datumEntity = datumService.getById(id);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", datumEntity);
    }

    /**
     * 分页查询所有Datum
     *
     * @param pageNo   页码
     * @param pageSize 每页条数
     * @return 分页查询的结果
     * @author 贾建清
     * @since 2.0.0 2018-12-08 12:31:48
     */
    @ApiOperation(value = "分页查询所有Datum")
    @GetMapping(value = {"/queryPageAll/{pageNo}/{pageSize}"})
    public ItooResult queryPageAll(@ApiParam(name = "pageNo", value = "页码", required = true, example = "1") @PathVariable Integer pageNo,
                                   @ApiParam(name = "pageSize", value = "页数", required = true, example = "10") @PathVariable Integer pageSize) {
        PageInfo<DatumEntity> datums = datumService.queryPageAll(pageNo, pageSize);
        return ItooResult.build(ItooResult.SUCCESS, "查询成功", datums);
    }

    //endregion

    /* **********************************以下为非模板生成的内容********************************* */

    /**
     * 上传模板
     *
     * @param uploadFile
     * @param questionTypeId
     * @return ItooResult 上传模板
     * @author 贾建清
     * @since 2.0.0 2018-12-08 12:31:48
     */
    @ApiOperation(value = "上传模板")
    @PostMapping(value = {"/uploadExcel/{questionTypeId}"})
    public ItooResult uploadExcel(@RequestParam("file") MultipartFile uploadFile, @ApiParam(value = "题型id", required = true) @PathVariable String questionTypeId) {
        DatumEntity datumEntity = new DatumEntity();
        try {
            if (uploadFile.isEmpty()) {
                return ItooResult.build(ItooResult.FAIL, "上传模板为空");
            }
            if (StringUtils.isEmpty(questionTypeId)) {
                return ItooResult.build(ItooResult.FAIL, "questionTypeId为空");
            }

            List<DatumModel> datumModelList = datumService.selectQuestionTypeId(questionTypeId);
            if (datumModelList.size() > 0) {

                return ItooResult.build(ItooResult.SUCCESS, "该题型模板已上传,请核对");
            } else {
                String originalFilenname = uploadFile.getOriginalFilename();
                datumEntity.setDatumName(originalFilenname);
                //取扩展名不用"."
                String extName = originalFilenname.substring(originalFilenname.lastIndexOf('.') + 1);
                FastDfsUtil client = new FastDfsUtil(URL);
                String urlString = client.uploadFile(uploadFile.getBytes(), extName);
                //服务器路径
                datumEntity.setDatumUrl(urlString);
                datumEntity.setQuestionTypeId(questionTypeId);
                datumService.save(datumEntity);

                return ItooResult.build(ItooResult.SUCCESS, "上传模板成功");

            }

        } catch (Exception e) {
            log.error("上传模板失败");
            return ItooResult.build(ItooResult.FAIL, "上传模板失败", e.getMessage());
        }
    }

    /**
     * 下载模板
     *
     * @param response
     * @param questionTypeId
     * @param datumName
     * @return ItooResult 下载模板
     * @author 贾建清
     * @since 2.0.0 2018-12-08 12:31:48
     */
    @ApiOperation(value = "下载模板")
    @GetMapping(value = {"/downExcel/{questionTypeId}/{datumName}"})
    public ItooResult downExcel(HttpServletResponse response, @ApiParam(value = "题型id", required = true) @PathVariable String questionTypeId, @ApiParam(value = "资料名称", required = true) @PathVariable String datumName) {
        if (StringUtils.isEmpty(questionTypeId)) {
            return ItooResult.build(ItooResult.FAIL, "questionTypeId为空");
        }

        if (StringUtils.isEmpty(datumName)) {
            return ItooResult.build(ItooResult.FAIL, "datumName为空");
        }

        String name = "模板";
        OutputStream outputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {

            String excelPath = datumService.queryExcelPath(questionTypeId);
            if (excelPath == null) {
                return ItooResult.build(ItooResult.FAIL, "获取数据为空");
            } else {
                FastDfsUtil client = new FastDfsUtil(URL);
                Date now = new Date();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String fileName = datumName + "模板" + dateFormat.format(now) + ".xls";
                outputStream = response.getOutputStream();
                //清空输出流
                response.reset();
                //设置导出文件的文件名
                response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("GBK"), "ISO8859-1"));
                //定义输出类型
                response.setContentType("application/msexcel;charset=UTF-8");
                bufferedOutputStream = new BufferedOutputStream(outputStream);
                client.downloadFile(excelPath, bufferedOutputStream);
                return ItooResult.build(ItooResult.SUCCESS, "下载模板成功");
            }

        } catch (Exception e) {
            log.error("下载模板失败");
            return ItooResult.build(ItooResult.FAIL, "下载模板失败", e.getMessage());
        } finally {
            try {
                if (bufferedOutputStream != null) {
                    bufferedOutputStream.flush();
                    bufferedOutputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                log.error("下载模板失败", e);
                return ItooResult.build(ItooResult.FAIL, "下载模板失败");
            }
        }
    }
}    
